<template>
    <el-select v-model="valueTemp" :loading="loading" :multiple="multiple" collapse-tags
      @change="changeSelect" :clearable="clearable" :filterable="filterable" :placeholder="placeholder">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.key"
        :value="item.value">
      </el-option>
    </el-select>
  </template>
  
  <script>
  import { useFetch } from '@/hooks/fetch'
  import { ref, onMounted } from 'vue'
  export default {
    name: "asyncSelect",
    props: {
      config: {
        type: Object,
        default: () => {}
      },
      placeholder: {
        type: String,
        default: '请选择'
      },
      filterable: {
        type: Boolean,
        default: true
      },
      clearable: {
        type: Boolean,
        default: true
      },
      multiple: {
        type: Boolean,
        default: false
      }
    },
    setup(props, { emit }) {
      const loading = ref(false)
      const valueTemp = ref('')
      const options = ref([])
      const { config } = props
      const placeholder = config?.placeholder || props.placeholder
      const multiple = config?.multiple || props.multiple
      const filterable = config?.filterable || props.filterable
      const clearable = config?.clearable || props.clearable
      const fetchData = async () => {
        const { fieldValue = undefined, fieldKey = undefined } = config || {}
        try {
          loading.value = true
          const { body, error } = await useFetch(config)
          if (error) {
            // console.log('asyncSelect--', error)
            emit('fetch', {"widgetName": 'asyncSelect', error})
            return
          }
          options.value = body.map(item => {
            return {
              'key': item[fieldKey || 'id'],
              'value': item[fieldValue || 'name']
            }
          })
        } finally {
          loading.value = false
        }
      }
      onMounted(() => {
        fetchData()
      })
      const changeSelect = id =>  {
        emit('event', id)
      }
    
      return {
          valueTemp, placeholder, clearable, filterable, multiple,
          loading, changeSelect, options
        }
      }
  }
</script>